<template>
  <!-- 添加/编辑对话框 -->
  <el-dialog :title="dialogTitle" v-model="visible" width="600px" @close="handleClose">
    <el-form :model="form" :rules="rules" ref="formRef" label-width="100px">
      <el-form-item label="任务名称" prop="name">
        <el-input v-model="form.name" placeholder="请输入任务名称" />
      </el-form-item>
      <el-form-item label="任务函数" prop="task_func">
        <el-select v-model="form.task_func" placeholder="请选择任务函数" filterable style="width: 100%">
          <el-option
            v-for="item in availableTasks"
            :key="item.name"
            :label="item.name"
            :value="item.name"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="任务定义" prop="task_definition">
        <el-select v-model="form.task_definition" placeholder="请选择任务定义" filterable style="width: 100%">
          <el-option
            v-for="item in taskDefinitions"
            :key="item.id"
            :label="item.name"
            :value="item.id"
          >
            <div style="display: flex; justify-content: space-between;">
              <span>{{ item.name }}</span>
              <span style="color: #8492a6; font-size: 13px">
                {{ formatTaskDefinitionDetail(item) }}
              </span>
            </div>
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="位置参数" prop="task_args">
        <div style="width: 100%">
          <el-button 
            size="small" 
            type="primary" 
            @click="addArg"
            style="margin-bottom: 10px"
          >
            + 添加参数
          </el-button>
          <div v-for="(arg, index) in taskArgs" :key="index" style="display: flex; margin-bottom: 8px; align-items: center;">
            <el-input 
              v-model="taskArgs[index]"
              placeholder="请输入参数值"
              style="flex: 1; margin-right: 10px"
            />
            <el-button 
              size="small" 
              type="danger" 
              @click="removeArg(index)"
            >
              删除
            </el-button>
          </div>
          <el-text v-if="taskArgs.length === 0" type="info" size="small">
            暂无位置参数,点击上方按钮添加
          </el-text>
        </div>
      </el-form-item>
      <el-form-item label="关键字参数" prop="task_kwargs">
        <div style="width: 100%">
          <el-button 
            size="small" 
            type="primary" 
            @click="addKwarg"
            style="margin-bottom: 10px"
          >
            + 添加参数
          </el-button>
          <div v-for="(item, index) in taskKwargs" :key="index" style="display: flex; margin-bottom: 8px; align-items: center;">
            <el-input 
              v-model="item.key"
              placeholder="参数名"
              style="width: 150px; margin-right: 10px"
            />
            <el-input 
              v-model="item.value"
              placeholder="参数值"
              style="flex: 1; margin-right: 10px"
            />
            <el-button 
              size="small" 
              type="danger" 
              @click="removeKwarg(index)"
            >
              删除
            </el-button>
          </div>
          <el-text v-if="taskKwargs.length === 0" type="info" size="small">
            暂无关键字参数,点击上方按钮添加
          </el-text>
        </div>
      </el-form-item>
      <el-form-item label="状态" prop="enabled">
        <el-switch
          v-model="form.enabled"
          active-text="启用"
          inactive-text="禁用"
        />
      </el-form-item>
      <el-form-item label="描述" prop="description">
        <el-input
          v-model="form.description"
          type="textarea"
          :rows="3"
          placeholder="请输入任务描述"
        />
      </el-form-item>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="handleClose">取消</el-button>
        <el-button type="primary" @click="handleSubmit">确定</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup>
import { ref, reactive, watch, computed } from 'vue'
import { ElMessage } from 'element-plus'
import requestUtil from '@/util/request'

const props = defineProps({
  modelValue: {
    type: Boolean,
    default: false
  },
  taskData: {
    type: Object,
    default: () => ({})
  },
  availableTasks: {
    type: Array,
    default: () => []
  },
  taskDefinitions: {
    type: Array,
    default: () => []
  }
})

const emit = defineEmits(['update:modelValue', 'refresh'])

const visible = computed({
  get: () => props.modelValue,
  set: (val) => emit('update:modelValue', val)
})

const formRef = ref(null)
const form = reactive({
  id: undefined,
  name: '',
  task_func: '',
  task_args: '[]',
  task_kwargs: '{}',
  enabled: true,
  description: '',
  task_definition: undefined
})

// 位置参数数组
const taskArgs = ref([])
// 关键字参数数组
const taskKwargs = ref([])

// 表单验证规则
const rules = reactive({
  name: [
    { required: true, message: '请输入任务名称', trigger: 'blur' },
    { min: 2, max: 50, message: '长度在 2 到 50 个字符', trigger: 'blur' }
  ],
  task_func: [
    { required: true, message: '请选择任务函数', trigger: 'change' }
  ],
  task_definition: [
    { required: true, message: '请选择任务定义', trigger: 'change' }
  ]
})

const dialogTitle = computed(() => {
  return form.id ? '编辑任务' : '添加任务'
})

// 添加位置参数
const addArg = () => {
  taskArgs.value.push('')
}

// 删除位置参数
const removeArg = (index) => {
  taskArgs.value.splice(index, 1)
}

// 添加关键字参数
const addKwarg = () => {
  taskKwargs.value.push({ key: '', value: '' })
}

// 删除关键字参数
const removeKwarg = (index) => {
  taskKwargs.value.splice(index, 1)
}

// 格式化时间间隔单位
const formatIntervalUnit = (unit) => {
  const unitMap = {
    'days': '天',
    'hours': '小时',
    'minutes': '分钟',
    'seconds': '秒',
    'microseconds': '微秒'
  }
  return unitMap[unit] || unit
}

// 格式化任务定义详情
const formatTaskDefinitionDetail = (definition) => {
  if (!definition) return ''
  
  if (definition.task_type === 'crontab' && definition.crontab_detail) {
    const c = definition.crontab_detail
    return `Crontab: ${c.minute} ${c.hour} ${c.day_of_month} ${c.month_of_year} ${c.day_of_week}`
  } else if (definition.task_type === 'interval' && definition.interval_detail) {
    return `间隔: ${definition.interval_detail.every} ${formatIntervalUnit(definition.interval_detail.period)}`
  } else if (definition.task_type === 'clock' && definition.clocked_detail) {
    return `时间: ${definition.clocked_detail.clocked_time}`
  }
  
  return definition.task_type
}

// 重置表单
const resetForm = () => {
  if (formRef.value) {
    formRef.value.resetFields()
  }
  
  form.id = undefined
  form.name = ''
  form.task_func = ''
  form.task_args = '[]'
  form.task_kwargs = '{}'
  form.enabled = true
  form.description = ''
  form.task_definition = undefined
  
  taskArgs.value = []
  taskKwargs.value = []
}

// 监听 taskData 变化
watch(() => props.taskData, (newData) => {
  if (newData && Object.keys(newData).length > 0) {
    // 填充表单数据
    form.id = newData.id
    form.name = newData.name
    form.task_func = newData.task_func
    form.task_definition = newData.task_definition
    form.enabled = newData.enabled
    form.description = newData.description
    
    // 处理位置参数
    if (newData.task_args && Array.isArray(newData.task_args) && newData.task_args.length > 0) {
      taskArgs.value = newData.task_args.map(arg => {
        if (typeof arg === 'string') {
          return arg
        }
        return JSON.stringify(arg)
      })
    } else {
      taskArgs.value = []
    }
    
    // 处理关键字参数
    if (newData.task_kwargs) {
      let kwargs = newData.task_kwargs
      if (typeof kwargs === 'string') {
        try {
          kwargs = JSON.parse(kwargs)
        } catch (e) {
          console.error('解析关键字参数失败', e)
          kwargs = {}
        }
      }
      
      taskKwargs.value = Object.entries(kwargs).map(([key, value]) => {
        return {
          key,
          value: typeof value === 'string' ? value : JSON.stringify(value)
        }
      })
    } else {
      taskKwargs.value = []
    }
  } else {
    resetForm()
  }
}, { deep: true, immediate: true })

// 关闭对话框
const handleClose = () => {
  resetForm()
  visible.value = false
}

// 提交表单
const handleSubmit = async () => {
  if (!formRef.value) return
  
  formRef.value.validate(async (valid) => {
    if (!valid) {
      return
    }
    
    try {
      const data = { ...form }
      
      // 处理位置参数 - 从数组转换
      data.task_args = taskArgs.value.map(arg => {
        if (arg === '') return ''
        
        // 尝试解析为数字
        if (!isNaN(arg) && arg.trim() !== '') {
          return Number(arg)
        }
        
        // 尝试解析为布尔值
        if (arg.toLowerCase() === 'true') return true
        if (arg.toLowerCase() === 'false') return false
        
        // 尝试解析为JSON对象或数组
        if (arg.startsWith('{') || arg.startsWith('[')) {
          try {
            return JSON.parse(arg)
          } catch (e) {
            // 解析失败，作为字符串
          }
        }
        
        return arg
      })
      
      // 处理关键字参数 - 从键值对数组转换为对象
      data.task_kwargs = {}
      for (const item of taskKwargs.value) {
        if (!item.key || !item.key.trim()) {
          ElMessage.warning('关键字参数的键不能为空')
          return
        }
        
        let value = item.value
        if (value === '') {
          data.task_kwargs[item.key] = ''
        } else if (!isNaN(value) && value.trim() !== '') {
          data.task_kwargs[item.key] = Number(value)
        } else if (value.toLowerCase() === 'true') {
          data.task_kwargs[item.key] = true
        } else if (value.toLowerCase() === 'false') {
          data.task_kwargs[item.key] = false
        } else if (value.startsWith('{') || value.startsWith('[')) {
          try {
            data.task_kwargs[item.key] = JSON.parse(value)
          } catch (e) {
            data.task_kwargs[item.key] = value
          }
        } else {
          data.task_kwargs[item.key] = value
        }
      }
      
      if (form.id) {
        await requestUtil.put(`tasks/tasks/${form.id}/`, data)
        ElMessage.success('更新成功')
      } else {
        await requestUtil.post('tasks/tasks/', data)
        ElMessage.success('创建成功')
      }
      
      handleClose()
      emit('refresh')
    } catch (error) {
      console.error('保存任务失败', error)
      if (error.response && error.response.data && error.response.data.error) {
        ElMessage.error(`保存失败: ${error.response.data.error}`)
      } else {
        ElMessage.error('保存任务失败')
      }
    }
  })
}
</script>

<style scoped>
.dialog-footer {
  text-align: right;
}
</style>
